package com.zhixing.controller;

import com.zhixing.common.properties.CustomerSwaggerProperties;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletResponse;

/**
 * swagger 2 word API
 *
 * @author zhixing
 */
@Slf4j
@Controller
@Api(tags = "Swagger2 转 word API")
@RequestMapping("/swagger-2-word")
public class Swagger2WordController {

    @Autowired
    private ISwagger2WordProcessor      swagger2WordProcessor;

    @Autowired
    private CustomerSwaggerProperties   customerSwaggerProperties;


    /**
     * Swagger 文档转后在线预览文件，可以通过右键另存为 xxx.doc 的方式另存为 word 文档
     * @param model 模板数据
     * @param url  swagger 地址
     * @return
     */
    @ApiOperation(value = "将 swagger 文档转换成 html 文档，可通过在网页上右键另存为 xxx.doc 的方式转换为 word 文档", response = String.class)
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功", response = String.class)})
    @RequestMapping(value = "/preview-online", method = {RequestMethod.GET})
    public String getWord(Model model,
                          @ApiParam(value = "swagger url 地址", required = false) @RequestParam(value = "url", required = false) String url,
                          @ApiParam(value = "需要生成文档的接口 tag 名称,多个试用使用英文逗号隔开", required = false) @RequestParam(value = "tags", required = false) String tags) {
        return swagger2WordProcessor.getWord(model,StringUtils.defaultIfBlank(url, customerSwaggerProperties.getSwaggerUrl()),tags);
    }

    /**
     * 将 swagger 文档一键下载为 doc 文档（所有数据）
     *
     * @param model
     * @param url      需要转换成 word 文档的资源地址
     * @param response
     */
    @ApiOperation(value = "根据 swagger url 文档地址转储 doc 文档", notes = "")
    @ApiResponses(value = {@ApiResponse(code = 200, message = "请求成功。")})
    @RequestMapping(value = "/download", method = {RequestMethod.GET})
    public void word(Model model,
                     @ApiParam(value = "swagger url 地址", required = false)      @RequestParam(required = false) String url,
                     @ApiParam(value = "下载后 word 文档名字", required = false)    @RequestParam(required = false) String fileName,
                     @ApiParam(value = "需要生成文档的接口 tag 名称,多个试用使用英文逗号隔开", required = false) @RequestParam(value = "tags", required = false) String tags,
                     HttpServletResponse response) {
        swagger2WordProcessor.word(model,StringUtils.defaultIfBlank(url, customerSwaggerProperties.getSwaggerUrl()),
                StringUtils.defaultIfBlank(fileName, customerSwaggerProperties.getFileName()),tags,response);
    }
}
